<template>
  <div>
    <el-form ref="deptForm" :rules="rules" label-width="120px" :model="form">
      <el-form-item label="部门名称" prop="name">
        <el-input v-model="form.name" style="width:80%" placeholder="1-50个字符" />
      </el-form-item>
      <el-form-item label="部门编码" prop="code">
        <el-input v-model="form.code" style="width:80%" placeholder="1-50个字符" />
      </el-form-item>
      <el-form-item label="部门负责人" prop="manager">
        <el-select v-model="form.manager" style="width:80%" placeholder="请选择">
          <el-option
            v-for="item in employeeData"
            :key="item.id"
            :value="item.username"
            :label="item.username"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="部门介绍" prop="introduce">
        <el-input v-model="form.introduce" style="width:80%" placeholder="1-300个字符" type="textarea" :rows="3" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="small" @click="hSubmit">确定</el-button>
        <el-button size="small" @click="hCancel">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { getEmployeeSimple, addDepartments, getDepartDetail, updateDepartments } from '@/api/departments'
export default {
  name: 'DeptDialog',
  // 接收父组件的id
  props: {
    pid: {
      type: String,
      required: true
    },
    isEdit: {
      type: Boolean,
      required: true
    },
    originList: {
      type: Array,
      default: () => []
    }
  },
  data() {
    // 校验部门编码是否重复
    const validCode = (rule, value, callback) => {
    // 将给个组织架构的编码取出，组成一个新的数组
      let existCodeList = this.originList.map(item => item.code)
      // 使用 includes 判断是否能否找到对应的部门，如果找到了则返回一个布尔值
      // 如果存在该对象，则说明编码已经存在，抛出错误
      // 如果不存在该对象，不做任何处理
      if (!this.isEdit) {
        // 在编辑界面是有非重复报错
      // 将给个组织架构的编码取出，组成一个新的数组
        existCodeList = this.originList.filter(item => item.id !== this.pid).map(item => item.name)
      }
      existCodeList.includes(value) ? callback(new Error('编码' + value + '已经存在')) : callback()
    }
    const validName = (rule, value, callback) => {
      let existNameList = this.originList.filter(item => item.pid === this.pid).map(item => item.name)
      // 判断状态是否为编辑
      if (!this.isEdit) {
        const dept = this.originList.find(item => item.pid === this.pid)

        // 获取当前项的pid
        const pid = dept.pid
        existNameList = this.originList.filter(item => item.pid === pid && item.id !== this.pid).map(item => item.name)
      }

      existNameList.includes(value) ? callback(new Error(`部门${value}已存在`)) : callback()
    }
    return {
      form: {
        name: '', // 部门名称
        code: '', // 部门编码
        manager: '', // 部门管理者
        introduce: '' // 部门介绍

      },
      // 表单验证
      rules: {
        name: [
          { required: true, message: '部门名称不能为空', trigger: 'blur' },
          { min: 1, max: 50, message: '部门名称要求1-50个字符', trigger: 'blur' },
          { validator: validName, trigger: 'blur' }
        ],
        code: [
          { required: true, message: '部门编码不能为空', trigger: 'blur' },
          { min: 1, max: 50, message: '部门编码要求1-50个字符', trigger: 'blur' },
          { validator: validCode, trigger: 'blur' }
        ],
        manager: [
          { required: true, message: '部门负责人不能为空', trigger: 'change' }
        ],
        introduce: [
          { required: true, message: '部门介绍不能为空', trigger: 'blur' },
          { min: 1, max: 300, message: '部门介绍要求1-300个字符', trigger: 'blur' }
        ]
      },
      employeeData: []
    }
  },
  created() {
    this.getEmployeeSimple()
    this.getDepartDetail()
  },
  methods: {
    // 根据ID获取部门详情
    async getDepartDetail() {
      // 判断是否是编辑页面
      if (!this.isEdit) {
        const res = await getDepartDetail(this.pid)
        this.form = res.data
      }
    },
    // 添加部门信息
    async addDepartments() {
      // 调用添加子组件api
      const res = await addDepartments({ ...this.form, pid: this.pid })
      this.$message(res.message)
      this.$emit('update-depart')
    },
    // 编辑部门信息
    async updateDepartments() {
      const res = await updateDepartments(this.form)
      this.$message(res.message)
      this.$emit('update-depart')
    },

    // 获取下拉员工数据
    async getEmployeeSimple() {
      const res = await getEmployeeSimple()
      this.employeeData = res.data
    },

    // 添加编辑确认按钮
    hSubmit() {
      // 判断当前添加信息是否是符合校验规则
      this.$refs.deptForm.validate(value => {
        if (value) {
          this.isEdit ? this.addDepartments() : this.updateDepartments()
        }
      })
    },

    // 取消编辑确认按钮
    hCancel() {
      // resetFields 是 element-ui 中的 el-form 组件提供一个 api，它的作用是：
      // 1. 重置表单数据
      // 2. 清空校验结果(页面上红色的提示)
      this.$refs.deptForm.resetFields()
      this.$emit('close')
    },
    resetForm() {
      this.$refs.deptForm.resetFields()
    }
  }
}
</script>

<style>

</style>
